<template>
    <div class="app-container">
        <!--      课表部分-->
        <div class="app-container">
<!--            一键排课按钮-->
            <div class="term">
                <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        @change="fetchCoursesForDateRange"
                        style="margin-right: 10px"
                />
                <!-- 学期选择按钮 -->
                <el-button type="primary" @click="selectTerm('第一学期')" plain>第一学期</el-button>
                <el-button type="success" @click="selectTerm('第二学期')" plain style="width: 92px">本学期</el-button>
                <el-button type="primary" @click="handleButtonClick" style="margin-right: 30px">一键排课</el-button>

            </div>
            <table style="width:80%;border-collapse:collapse;margin: 0 auto" border="2">
                <thead style="border:1px solid black;">
                <tr>
                    <!-- 空白单元格用于对齐 -->
                    <th width="48" class="fw">课程表</th>
                    <!-- 使用 datelist 作为横坐标 -->
                    <th class="fw" v-for="(day, index) in datelist" :key="index">
                        <p>{{ day }}</p>
                    </th>
                </tr>
                </thead>
                <tbody style="border:1px solid black;">
                <!-- 使用 dayList 的值作为纵坐标 -->
                <tr v-for="(time, timeIndex) in dayList" :key="timeIndex" class="tr">
                    <td class="td">
                        <!-- 使用 dayList 的值作为纵坐标的显示 -->
                        <p>{{ time }}</p>
                    </td>
                    <!-- 使用 dataList 的内层数组作为横坐标 -->
                    <td v-for="(course, dayIndex) in dataList[timeIndex]" :key="dayIndex" :style="{ backgroundColor: course ? course.color : '' }" class="td">
                        <template v-if="course">
                            <p>{{ course.name }}</p>
                            <p>{{ course.classroom }}</p>
                            <p>{{ course.userName }}</p>
                        </template>
                        <template v-else>
                            <!-- 空白单元格 -->
                            <p>---</p>
                        </template>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <!--      查询部分-->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item label="课程名称" prop="name">
                <el-input
                        v-model="queryParams.name"
                        placeholder="请输入课程名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item label="课程学期" prop="term" style="width: 300px">
                <el-select v-model="queryParams.term" placeholder="请选择课程学期" clearable>
                    <el-option
                            v-for="dict in course_term"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="课时安排" prop="arrangement">
                <el-select v-model="queryParams.arrangement" placeholder="请选择课时安排"  style="width: 200px"  clearable>
                    <el-option
                            v-for="dict in course_arrangement"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>

            <el-form-item label="开始日期" prop="starttime" label-width="100px">
                <el-date-picker clearable
                                v-model="queryParams.starttime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择开始日期"
                                style="width: 198px"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" prop="endtime" label-width="100px">
                <el-date-picker clearable
                                v-model="queryParams.endtime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择结束日期"
                                style="width: 198px">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="星期选择" prop="courseweek"  label-width="100px">
                <el-select v-model="queryParams.courseweek" placeholder="请选择星期" style="width: 200px" clearable>
                    <el-option
                            v-for="dict in user_week"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <!--    批量操作-->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['courseManager:courseManager:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['courseManager:courseManager:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!--    表格部分-->
        <el-table v-loading="loading" :data="courseManagerList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="课程名称" align="center" prop="name" />
            <!--      <el-table-column label="学时" align="center" prop="hours" />-->
            <!--      <el-table-column label="学分" align="center" prop="credits" />-->
            <el-table-column label="课程学期" align="center" prop="term">
                <template #default="scope">
                    <dict-tag :options="course_term" :value="scope.row.term"/>
                </template>
            </el-table-column>
            <el-table-column label="课时安排" align="center" prop="arrangement">
                <template #default="scope">
                    <dict-tag :options="course_arrangement" :value="scope.row.arrangement"/>
                </template>
            </el-table-column>
            <el-table-column label="星期" align="center" prop="courseweek">
                <template #default="scope">
                    <dict-tag :options="user_week" :value="scope.row.courseweek"/>
                </template>
            </el-table-column>
            <!--            <el-table-column label="课程描述" align="center" prop="coursedesc" />-->
<!--            <el-table-column label="课程描述" align="center" prop="coursedesc">-->
<!--                <template #default="scope">-->
<!--                    <div class="cell-content">-->
<!--                        {{ scope.row.coursedesc }}-->
<!--                    </div>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column label="教室" align="center" prop="classroom" />
            <!--      <el-table-column label="人数" align="center" prop="maxnum" />-->
            <el-table-column label="图片" align="center" prop="imgs" width="100">
                <template #default="scope">
                    <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
                </template>
            </el-table-column>
                  <el-table-column label="开始日期" align="center" prop="starttime" width="180">
                    <template #default="scope">
                      <span>{{ parseTime(scope.row.starttime, '{y}-{m}-{d}') }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="结束日期" align="center" prop="endtime" width="180">
                    <template #default="scope">
                      <span>{{ parseTime(scope.row.endtime, '{y}-{m}-{d}') }}</span>
                    </template>
                  </el-table-column>

            <!--      <el-table-column label="用户编号" align="center" prop="userId" />-->
            <!--      <el-table-column label="老师编号" align="center" prop="teacherId" />-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['courseManager:courseManager:edit']">修改</el-button>
                    <!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['courseManager:courseManager:remove']">删除</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <!--    分页-->
        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />
        <!--  添加或修改排课管理模态框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="courseManagerRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="课程名称" prop="name" >
                    <el-input v-model="form.name" placeholder="请输入课程名称" disabled/>
                </el-form-item>
                <!--        <el-form-item label="学时" prop="hours">-->
                <!--          <el-input v-model="form.hours" placeholder="请输入学时" />-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="学分" prop="credits">-->
                <!--          <el-input v-model="form.credits" placeholder="请输入学分" />-->
                <!--        </el-form-item>-->
                <el-form-item label="课程学期" prop="term" >
                    <el-select v-model="form.term" placeholder="请选择课程学期" disabled>
                        <el-option
                                v-for="dict in course_term"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <!--             老师姓名-->
                <el-form-item label="老师" prop="userId">
                    <el-input v-model="form.teacher.userName" placeholder="请选择老师" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="教室" prop="classroom">
                    <el-input v-model="form.classroom" placeholder="请输入教室" disabled/>
                </el-form-item>
                <el-form-item label="开始日期" prop="starttime">
                    <el-date-picker clearable
                                    v-model="form.starttime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择开始日期"

                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束日期" prop="endtime">
                    <el-date-picker clearable
                                    v-model="form.endtime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择结束日期"

                    >
                    </el-date-picker>
                </el-form-item>
                <!--          下面为老师可设置的-->
                <!--                <el-form-item label="课程描述" prop="coursedesc">-->
                <!--                    <el-input v-model="form.coursedesc" placeholder="请输入课程描述" />-->
                <!--                </el-form-item>-->
<!--                <el-form-item label="课程描述" prop="coursedesc">-->
<!--                    <el-input-->
<!--                            type="textarea"-->
<!--                            v-model="form.coursedesc"-->
<!--                            placeholder="请输入课程描述"-->
<!--                            :autosize="{ minRows: 1, maxRows: 4 }"-->
<!--                            maxlength="200"-->
<!--                            show-word-limit-->
<!--                    />-->
<!--                </el-form-item>-->

                <el-form-item label="图片" prop="imgs">
                    <image-upload v-model="form.imgs" limit="1"/>
                </el-form-item>


                <el-form-item label="课时安排" prop="arrangement">
                    <el-select v-model="form.arrangement" placeholder="请选择课时安排">
                        <el-option
                                v-for="dict in course_arrangement"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="星期" prop="courseweek">
                    <el-select v-model="form.courseweek" placeholder="请选择星期">
                        <el-option
                                v-for="dict in user_week"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="CourseManager">
    import { listCourseManager,listCourseManagerOne, getCourseManager, delCourseManager, addCourseManager, updateCourseManager } from "@/api/courseManager/courseManager";
    import {ref, reactive, onMounted} from "vue";

    const { proxy } = getCurrentInstance();
    const { course_arrangement, course_term, user_week } = proxy.useDict('course_arrangement', 'course_term', 'user_week');
    const courseManagerList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");
    const datelist  = ref([ '星期一', '星期二', '星期三', '星期四', '星期五', '星期六','星期日']);
    const dayList = ref(['第一节课', '第二节课', '第三节课', '第四节课']);
    const dataList = ref([]);
    /** 一键排课*/
    const handleButtonClick = () => {
        //添加一个确认框
        proxy.$confirm("一键排课会会覆盖原有排课，是否继续？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            // 继续执行排课操作
            listCourseManagerOne({
                pageNum:  1,
                pageSize:  1000,
            });
            selectTerm(currentTerm);
        //    刷新页面
            location.reload()

        }).catch(() => {
            // 取消操作
            proxy.$message({
                type: "info",
                message: "已取消一键排课",
            });
        });

    };
    /**课表管理*/
    let currentTerm = '第二学期'; // 初始化为第一学期
    const selectTerm = (term) => {
        currentTerm = term;
        fetchData({ term }).then(data => {
            dataList.value = processData(data);
        });
    };
    let colorList = [];
    const generateColorList = () => {
        colorList = [];
        for (let i = 0; i < 10; i++) {
            let r = Math.floor(Math.random() * 128) + 128;
            let g = Math.floor(Math.random() * 128) + 128;
            let b = Math.floor(Math.random() * 128) + 128;
            let color = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
            colorList.push(color);
        }
    };
    const processData = (data) => {
        const { rows } = data;
        const schedule = Array.from({ length: dayList.value.length }, () => Array(datelist.value.length).fill(null));
        // 生成颜色列表
        generateColorList();

        rows.forEach((row, rowIndex) => {
            const dayIndex = datelist.value.indexOf(row.courseweek);
            const timeIndex = dayList.value.indexOf(row.arrangement);
            if (dayIndex !== -1 && timeIndex !== -1) {
                schedule[timeIndex][dayIndex] = {
                    name: row.name,
                    classroom: row.classroom,
                    userName: row.teacher.userName,
                    // 分配颜色
                    color: colorList[rowIndex % colorList.length], // 防止颜色列表不足
                };
            }
        });

        return schedule;
    };

    onMounted(() => {
        selectTerm(currentTerm);
    });

    const fetchData = async (query) => {
        try {
            const response = await listCourseManager({
                ...query,
                pageNum: query.pageNum || 1,
                pageSize: query.pageSize || 40,
            });
            return response;
        } catch (error) {
            console.error('Failed to fetch data:', error);
        }
    };
    //
    function validateDate(rule, value, callback) {
        if (!value) {
            return callback(new Error('请选择日期'));
        }

        // 获取当前日期
        const currentDate = new Date();

        // 解析form表单中的years值，假设形式为"2023-2024"
        const years = form.value.years.split('-');
        const endYear = parseInt(years[1], 10);
        const endOfYear = new Date(endYear, 11, 31); // 11代表12月，因为JavaScript的月份是从0开始计数的

        // 检查日期是否小于当前日期
        const selectedDate = new Date(value);
        if (selectedDate < currentDate) {
            return callback(new Error('日期不能小于当前日期'));
        }

        // 检查日期是否大于结束年份的年底
        if (selectedDate > endOfYear) {
            return callback(new Error(`日期不能大于${endYear}年底`));
        }

        callback();
    }
    const data = reactive({
        form: {},
        queryParams: {
            pageNum: 1,
            pageSize: 40,
            name: null,
            term: null,
            arrangement: null,
            coursedesc: null,
            classroom: null,
            maxnum: null,
            imgs: null,
            starttime: null,
            endtime: null,
            courseweek: null,
            userId: null,
            teacherId: null
        },
        rules: {
            name: [
                { required: true, message: "课程名称不能为空", trigger: "blur" }
            ],
            starttime: [
                { required: true, message: "开始日期不能为空", trigger: "blur" },
                { validator: validateDate, trigger: "blur" }
            ],
            endtime: [
                { required: true, message: "结束日期不能为空", trigger: "blur" },
                {
                    validator: (rule, value, callback) => {
                        if (!value) {
                            return callback(new Error('请选择结束日期'));
                        }
                        if (!form.value.starttime) {
                            return callback(new Error('开始日期未选择，无法比较结束日期'));
                        }
                        const startTime = new Date(form.value.starttime);
                        const endTime = new Date(value);
                        if (endTime <= startTime) {
                            return callback(new Error('结束日期必须晚于开始日期'));
                        }
                        callback();
                    },
                    trigger: "blur"
                },
            ],
        }
    });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询排课管理列表 */
    function getList() {
        loading.value = true;
        listCourseManager(queryParams.value).then(response => {
            courseManagerList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
            id: null,
            name: null,
            hours: null,
            credits: null,
            term: null,
            arrangement: null,
            coursedesc: null,
            classroom: null,
            maxnum: null,
            imgs: null,
            starttime: null,
            endtime: null,
            courseweek: null,
            userId: null,
            teacher: {
                userId: null,
                userName: null
            }
        };
        proxy.resetForm("courseManagerRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加排课管理";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _id = row.id || ids.value
        getCourseManager(_id).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改排课管理";
        });
    }

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["courseManagerRef"].validate(valid => {
            if (valid) {
                if (form.value.id != null) {
                    updateCourseManager(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                        selectTerm(currentTerm);

                    });
                } else {
                    addCourseManager(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                        selectTerm(currentTerm);

                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _ids = row.id || ids.value;
        proxy.$modal.confirm('是否确认删除排课管理编号为"' + _ids + '"的数据项？').then(function() {
            return delCourseManager(_ids);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    }

    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('courseManager/courseManager/export', {
            ...queryParams.value
        }, `courseManager_${new Date().getTime()}.xlsx`)
    }

    getList();
</script>
<style lang="scss" scoped>
  .term{
    //  右对齐
    text-align: right;
    margin-bottom: 5px;
    margin-right: 130px;
  }
  .course-cell {
    background-color: var(--cell-color);
  }
  .tabel-container {
    padding: 60px;
    padding-top: 20px;
  }

  .tr {
    height: 80px;

    .td {
      width: 180px;
      text-align: center;
      border: 1px solid black;
    }
  }

  td p {
    margin: 0;
    padding: 0;
  }

  .Micro_top {
    background-color: #fff;
    //   width: 1200px;
    margin: 0 auto;
    border-radius: 4px;

    padding-top: 24px;
    height: 120px;
    margin-bottom: 25px;

    .searchs,
    .searchd,
    .title {
      padding: 0 24px;
    }

    .searchs,
    .searchd,
    .versionbox {
      display: flex;
      font-size: 14px;
      color: #333333;
      margin-bottom: 24px;
      height: 24px;

      span {
        display: inline-block;
        font-weight: 600;

        font-size: 16px;
        color: #282d30;
        line-height: 24px;
      }

      ul {
        display: flex;
        flex-wrap: wrap;

        // padding-top: 14px;
        padding-left: 26px;

        li {
          cursor: pointer;
          padding: 0 12px;
          font-size: 16px;
          color: #36363a;
          line-height: 24px;
          margin-right: 36px;
          min-width: 56px;
          height: 24px;
          line-height: 24px;
        }

        .active {
          background-color: #00c15d;
          border-radius: 5px;
          color: rgba(255, 255, 255, 1);
        }
      }

      em {
        line-height: 54px;
        font-style: normal;
        color: #00c15d;
        cursor: pointer;

        img {
          margin-left: 8px;
        }
      }
    }
  }
  .content {
    //   width: 1200px;
    margin: 0 auto;

    background-color: #fff;
  }
  .cell-content {
    display: -webkit-box;
    -webkit-line-clamp: 3; /* 控制显示的行数 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>



